// 内存中存储房间（生产环境应该用 Redis）
const rooms = new Map();

// 存储用户游戏记录（用于获取最近一起玩的好友）
// 结构: userId -> Set([friendUserId1, friendUserId2, ...])
const userGameHistory = new Map();

// 存储用户在线状态
// 结构: userId -> { userName, avatar, lastActiveTime, isOnline }
const userOnlineStatus = new Map();

class GameService {
  // 获取房间列表
  static getRoomList() {
    const roomList = [];
    rooms.forEach((room, roomId) => {
      roomList.push({
        roomId,
        roomName: room.roomName,
        hasPassword: !!room.password,
        currentPlayers: room.players.length,
        maxPlayers: room.maxPlayers,
        status: room.status, // waiting, playing
        owner: room.players.find(p => p.isOwner)?.userName || '',
        createdAt: room.createdAt
      });
    });
    return roomList.sort((a, b) => b.createdAt - a.createdAt);
  }

  // 创建房间
  static createRoom(roomName, password, maxPlayers, userId, userName) {
    const roomId = 'R' + Date.now().toString(36).toUpperCase() + Math.random().toString(36).substr(2, 4).toUpperCase();
    
    const room = {
      roomId,
      roomName: roomName || `${userName}的房间`,
      password,
      maxPlayers: maxPlayers || 3,
      players: [{
        userId,
        userName,
        isReady: false,
        isOwner: true,
        joinedAt: Date.now()
      }],
      status: 'waiting',
      createdAt: Date.now()
    };

    rooms.set(roomId, room);
    
    // 更新用户在线状态
    this.updateUserOnlineStatus(userId, userName);
    
    return { roomId, ...room };
  }

  // 加入房间
  static joinRoom(roomId, password, userId, userName) {
    const room = rooms.get(roomId);
    if (!room) {
      throw new Error('房间不存在或已解散');
    }

    if (room.password && room.password !== password) {
      throw new Error('房间密码错误');
    }

    if (room.players.length >= room.maxPlayers) {
      throw new Error('房间已满');
    }

    if (room.status === 'playing') {
      throw new Error('游戏进行中，无法加入');
    }

    // 检查是否已在房间中
    const existingPlayer = room.players.find(p => p.userId === userId);
    if (existingPlayer) {
      return room;
    }

    room.players.push({
      userId,
      userName,
      isReady: false,
      isOwner: false,
      joinedAt: Date.now()
    });

    // 记录用户交互历史
    this.recordPlayerInteraction(roomId);
    
    // 更新用户在线状态
    this.updateUserOnlineStatus(userId, userName);

    return room;
  }

  // 离开房间
  static leaveRoom(roomId, userId) {
    const room = rooms.get(roomId);
    if (!room) {
      throw new Error('房间不存在');
    }

    const playerIndex = room.players.findIndex(p => p.userId === userId);
    if (playerIndex === -1) {
      throw new Error('您不在该房间中');
    }

    const player = room.players[playerIndex];
    room.players.splice(playerIndex, 1);

    // 如果房主离开，转移房主权限或删除房间
    if (player.isOwner) {
      if (room.players.length > 0) {
        room.players[0].isOwner = true;
      } else {
        rooms.delete(roomId);
      }
    }

    return room;
  }

  // 获取房间详情
  static getRoomDetail(roomId) {
    const room = rooms.get(roomId);
    if (!room) {
      throw new Error('房间不存在');
    }
    return room;
  }

  // 准备/取消准备
  static toggleReady(roomId, userId) {
    const room = rooms.get(roomId);
    if (!room) {
      throw new Error('房间不存在');
    }

    const player = room.players.find(p => p.userId === userId);
    if (!player) {
      throw new Error('您不在该房间中');
    }

    if (player.isOwner) {
      throw new Error('房主不需要准备');
    }

    player.isReady = !player.isReady;
    return room;
  }

  // 开始游戏（暂未实现，预留接口）
  static startGame(roomId, userId) {
    const room = rooms.get(roomId);
    if (!room) {
      throw new Error('房间不存在');
    }

    const player = room.players.find(p => p.userId === userId);
    if (!player || !player.isOwner) {
      throw new Error('只有房主可以开始游戏');
    }

    if (room.players.length !== room.maxPlayers) {
      throw new Error(`需要 ${room.maxPlayers} 名玩家才能开始`);
    }

    room.status = 'playing';
    return { msg: '游戏开始，具体逻辑待实现' };
  }

  // 游戏相关接口预留
  static showBlackA(roomId, userId, cardId) {
    throw new Error('游戏功能待实现');
  }

  static showRedA(roomId, userId, cardId) {
    throw new Error('游戏功能待实现');
  }

  static playCards(roomId, userId, cards) {
    throw new Error('游戏功能待实现');
  }

  static passCards(roomId, userId) {
    throw new Error('游戏功能待实现');
  }

  static getGameStatus(roomId, userId) {
    throw new Error('游戏功能待实现');
  }

  // 调试方法：获取所有房间（包括密码）
  static debugGetAllRooms() {
    const roomList = [];
    rooms.forEach((room, roomId) => {
      roomList.push({
        roomId,
        roomName: room.roomName,
        password: room.password || '无密码', // 显示实际密码
        hasPassword: !!room.password,
        currentPlayers: room.players.length,
        maxPlayers: room.maxPlayers,
        status: room.status,
        owner: room.players.find(p => p.isOwner)?.userName || '',
        players: room.players,
        createdAt: room.createdAt
      });
    });
    return roomList.sort((a, b) => b.createdAt - a.createdAt);
  }

  // 更新用户在线状态
  static updateUserOnlineStatus(userId, userName, avatar) {
    userOnlineStatus.set(userId, {
      userName,
      avatar,
      lastActiveTime: Date.now(),
      isOnline: true
    });
  }

  // 记录用户游戏历史（当游戏结束时调用）
  static recordGameHistory(playerIds) {
    // playerIds 是参与游戏的所有玩家ID数组
    playerIds.forEach(userId => {
      if (!userGameHistory.has(userId)) {
        userGameHistory.set(userId, new Set());
      }
      const userHistory = userGameHistory.get(userId);
      
      // 将其他玩家添加到该用户的游戏历史中
      playerIds.forEach(otherId => {
        if (otherId !== userId) {
          userHistory.add(otherId);
        }
      });
    });
  }

  // 当用户加入房间时记录历史
  static recordPlayerInteraction(roomId) {
    const room = rooms.get(roomId);
    if (!room || room.players.length < 2) return;

    const playerIds = room.players.map(p => p.userId);
    playerIds.forEach(userId => {
      if (!userGameHistory.has(userId)) {
        userGameHistory.set(userId, new Set());
      }
      const userHistory = userGameHistory.get(userId);
      
      // 将其他玩家添加到该用户的游戏历史中
      playerIds.forEach(otherId => {
        if (otherId !== userId) {
          userHistory.add(otherId);
        }
      });
    });
  }

  // 获取最近一起玩过的好友列表
  static getRecentFriends(userId) {
    // 更新该用户的在线状态
    const currentUser = userOnlineStatus.get(userId);
    if (currentUser) {
      currentUser.lastActiveTime = Date.now();
      currentUser.isOnline = true;
    }

    // 清理过期的在线状态（30分钟未活动视为离线）
    const OFFLINE_THRESHOLD = 30 * 60 * 1000; // 30分钟
    userOnlineStatus.forEach((status, uid) => {
      if (Date.now() - status.lastActiveTime > OFFLINE_THRESHOLD) {
        status.isOnline = false;
      }
    });

    const friendIds = userGameHistory.get(userId);
    if (!friendIds || friendIds.size === 0) {
      return [];
    }

    const friends = [];
    friendIds.forEach(friendId => {
      // 从所有房间中查找该好友的信息
      let friendInfo = null;
      rooms.forEach(room => {
        const player = room.players.find(p => p.userId === friendId);
        if (player && !friendInfo) {
          friendInfo = {
            userId: player.userId,
            userName: player.userName,
            avatar: player.avatar || '/static/images/profile.jpg'
          };
        }
      });

      // 如果在房间中没找到，从在线状态中查找
      if (!friendInfo) {
        const onlineStatus = userOnlineStatus.get(friendId);
        if (onlineStatus) {
          friendInfo = {
            userId: friendId,
            userName: onlineStatus.userName,
            avatar: onlineStatus.avatar || '/static/images/profile.jpg'
          };
        }
      }

      if (friendInfo) {
        const status = userOnlineStatus.get(friendId);
        friends.push({
          ...friendInfo,
          isOnline: status ? status.isOnline : false,
          lastActiveTime: status ? status.lastActiveTime : 0
        });
      }
    });

    // 按最后活跃时间排序
    return friends.sort((a, b) => (b.lastActiveTime || 0) - (a.lastActiveTime || 0));
  }
}

module.exports = GameService;
